package com.pysrc.base.interceptor;


import com.pysrc.base.annotation.InterAnnotation;
import com.pysrc.base.constant.UserRole;
import com.pysrc.base.entity.SysUser;
import com.pysrc.base.service.SysUserService;
import org.springframework.http.HttpStatus;
import org.springframework.lang.Nullable;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.List;

/**
 * @ClassName:
 * @Auther L.Chen
 * @CreateDate
 * @Description TODO
 */
public class FirstInterceptor implements HandlerInterceptor {
    private SysUserService service;
    public FirstInterceptor(SysUserService service){
        this.service = service;
    }
    private void bad(HttpServletResponse response) throws IOException {
        response.setHeader("Content-Type","application/json;charset=UTF-8");
        response.setStatus(HttpStatus.FORBIDDEN.value());
        response.getWriter().write(String.format("{\"status\":%d,\"message:\":\"请求被拒绝\"}", HttpStatus.FORBIDDEN.value()));
        response.getWriter().close();
    }
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userId = request.getHeader("userId");
        if(null==userId||"".equals(userId)){
            bad(response);
            return false;
        }
        SysUser sysUser = new SysUser();
        sysUser.setUserId(new Long(userId));
        List<SysUser> users = service.select(sysUser);
        if(null==users||users.size()==0){
            bad(response);
            return false;
        }
        Method method = ((HandlerMethod) handler).getMethod();
        InterAnnotation annotation = method.getAnnotation(InterAnnotation.class);
        if(annotation!=null&&annotation.validate()){ // 不为空，且需要校验
            if(!UserRole.ADMIN.name().equals(users.get(0).getUserRole())){
                bad(response);
                return false;
            }
        }
        return true;
    }
}
